import sys

class PacketProcessor:
	""" Class for processing tcp packets,
	and make DC++ packets. (Merge packets from
	one command). """
	def __init__(self):
		""" Clear buffer and initialize class. """
		buffer = ""

        def _isFull(self, command):
		""" Check buffer for full command. """
                if len(command) == 0:
                        return False
                if command[len(command) - 1] == '|':
                        return True
                else:
                        return False

	def Process(self, socket, packet, commandProcessor):
		""" Process new tcp packet. """
		# Save previous packets
		prev = self.buffer
		# Clear buffer
		self.buffer = ""
		# Merge previous and packet
                buf = prev + packet
		# Split
                commands = buf.split('|')
		# If Merge result not is full command.
                if not self._isFull(buf):
			# If count of commands in Merge result is 1
                        if len(commands) == 1:
				# Save Merge result to buffer
                                self.buffer  = commands[0]
                                commands = []
                        else:
				# Save first from all commands to buffer
                                self.buffer = commands[len(commands) - 1]
                                commands = commands[0:len(commands)-1]
		# Process every command
                for i in commands:
                        commandProcessor(i, socket)

	def ClearBuffer(self):
		self.buffer = ""


def createKey(lock):
	""" Function create key from lock for DC connections. """
	key = {}
        for i in xrange(1, len(lock)):
                key[i] = ord(lock[i]) ^ ord(lock[i-1])
        key[0] = ord(lock[0]) ^ ord(lock[len(lock)-1]) ^ ord(lock[len(lock)-2]) ^ 5
        for i in xrange(0, len(lock)):
                key[i] = ((key[i]<<4) & 240) | ((key[i]>>4) & 15)
        out = ''
        for i in xrange(0, len(lock)):
                out += unichr(key[i])
        out = out.replace(u'\0', u'/%DCN000%/').replace(u'\5', u'/%DCN005%/').replace(u'\44', u'/%DCN036%/')
        out = out.replace(u'\140', u'/%DCN096%/').replace(u'\174', u'/%DCN124%/').replace(u'\176', u'/%DCN126%/')
        return out

